// 页面导出为pdf格式
import html2Canvas from 'html2canvas';
import jsPDF from 'jspdf';

const htmlToPdf = {
    getPdf(title, id) {
        this.handleCrossOriginImages()
        this.waitForAllImages()
        html2Canvas(document.querySelector(id), {
            allowTaint: false,
            taintTest: false,
            logging: false,
            useCORS: true,
            dpi: window.devicePixelRatio * 4, //将分辨率提高到特定的DPI 提高四倍
            scale: 4, //按比例增加分辨率
        }).then((canvas) => {
            var pdf = new jsPDF('p', 'mm', 'a4'); //A4纸，纵向
            var ctx = canvas.getContext('2d'),
                a4w = 190,
                a4h = 272, //A4大小，210mm x 297mm，四边各保留10mm的边距，显示区域190x277
                imgHeight = Math.floor((a4h * canvas.width) / a4w), //按A4显示比例换算一页图像的像素高度
                renderedHeight = 0;

            while (renderedHeight < canvas.height) {
                var page = document.createElement('canvas');
                page.width = canvas.width;
                page.height = Math.min(imgHeight, canvas.height - renderedHeight); //可能内容不足一页

                //用getImageData剪裁指定区域，并画到前面创建的canvas对象中
                page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight),), 0, 0,);
                pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, (a4w * page.height) / page.width),); //添加图像到页面，保留10mm边距

                renderedHeight += imgHeight;
                if (renderedHeight < canvas.height) {
                    // pdf.addPage(); //如果后面还有内容，添加一个空页
                }
                // delete page;
            }
            // pdf.save(title + '.pdf')
            // 在新窗口中打开PDF
            const pdfBlob = pdf.output('blob')
            const pdfUrl = URL.createObjectURL(pdfBlob)
            window.open(pdfUrl, '_blank')
        });
    },
    async waitForAllImages() {
        return new Promise((resolve) => {
            const images = document.querySelectorAll('img')
            const imagePromises = []

            images.forEach(img => {
                if (img.complete && img.naturalHeight !== 0) {
                    return // 图片已加载
                }

                const promise = new Promise((imgResolve) => {
                    const onLoad = () => {
                        img.removeEventListener('load', onLoad)
                        img.removeEventListener('error', onError)
                        imgResolve()
                    }

                    const onError = () => {
                        img.removeEventListener('load', onLoad)
                        img.removeEventListener('error', onError)
                        // 设置占位图片
                        img.src = this.generatePlaceholderImage(
                            img.width || 50,
                            img.height || 50,
                            '图片加载失败'
                        )
                        imgResolve()
                    }

                    img.addEventListener('load', onLoad)
                    img.addEventListener('error', onError)
                })

                imagePromises.push(promise)
            })

            if (imagePromises.length === 0) {
                resolve()
            } else {
                Promise.all(imagePromises).then(resolve)
            }
        })
    },
    async handleCrossOriginImages() {
        const images = document.querySelectorAll('img')

        for (let img of images) {
            if (img.src.startsWith('http') && !img.src.includes(window.location.hostname)) {
                try {
                    // 尝试转换为blob URL
                    const response = await fetch(img.src, { mode: 'cors' })
                    const blob = await response.blob()
                    const objectUrl = URL.createObjectURL(blob)

                    // 创建新的图片元素
                    const newImg = new Image()
                    newImg.crossOrigin = 'anonymous'

                    await new Promise((resolve, reject) => {
                        newImg.onload = resolve
                        newImg.onerror = reject
                        newImg.src = objectUrl
                    })

                    // 替换原图片
                    img.src = objectUrl

                    // 清理URL对象
                    setTimeout(() => URL.revokeObjectURL(objectUrl), 60000)

                } catch (error) {
                    console.warn('跨域图片处理失败:', img.src, error)
                    // 使用占位图片
                    img.src = this.generatePlaceholderImage(
                        img.naturalWidth || 800,
                        img.naturalHeight || 600,
                        '跨域图片'
                    )
                }
            }
        }
    },
    generatePlaceholderImage(width, height, text) {
        const canvas = document.createElement('canvas')
        canvas.width = width
        canvas.height = height
        const ctx = canvas.getContext('2d')

        // 背景
        ctx.fillStyle = '#f5f5f5'
        ctx.fillRect(0, 0, width, height)

        // 边框
        ctx.strokeStyle = '#ddd'
        ctx.lineWidth = 2
        ctx.strokeRect(1, 1, width - 2, height - 2)

        // 文字
        ctx.fillStyle = '#999'
        ctx.font = 'bold 24px Arial'
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'
        ctx.fillText(text, width / 2, height / 2)

        return canvas.toDataURL('image/png')
    }
};

export default htmlToPdf;